<template>
  <div class="dashboard">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon users">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.totalUsers }}</h3>
              <p>总用户数</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon active">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.activeUsers }}</h3>
              <p>活跃用户</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon today">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.todayUsers }}</h3>
              <p>今日新增</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon growth">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.growthRate }}%</h3>
              <p>增长率</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>系统信息</span>
          </template>
          <div class="system-info">
            <p><strong>系统版本：</strong>PAAS v1.0.0</p>
            <p><strong>运行环境：</strong>Spring Boot + Vue 3</p>
            <p><strong>数据库：</strong>MySQL 8.0</p>
            <p><strong>运行时间：</strong>{{ uptime }}</p>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>最近活动</span>
          </template>
          <el-timeline>
            <el-timeline-item
              v-for="activity in recentActivities"
              :key="activity.id"
              :timestamp="activity.time"
            >
              {{ activity.description }}
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { User, UserFilled, Calendar, TrendCharts } from '@element-plus/icons-vue'
import { userApi } from '@/api/user'
import { studyApi } from '@/api/study'
import { personalApi } from '@/api/personal'

export default {
  name: 'Dashboard',
  components: {
    User,
    UserFilled,
    Calendar,
    TrendCharts
  },
  setup() {
    const store = useStore()

    const stats = ref({
      totalUsers: 0,
      activeUsers: 0,
      todayUsers: 0,
      growthRate: 0
    })
    
    const uptime = ref('')
    const recentActivities = ref([])

    const formatPercent = (num) => {
      if (!num || isNaN(num)) return 0
      return Number(num.toFixed(2))
    }

    const isSameDay = (isoString) => {
      if (!isoString) return false
      const d = new Date(isoString)
      const now = new Date()
      return d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() && d.getDate() === now.getDate()
    }

    const loadStats = async () => {
      try {
        const res = await userApi.getUsers()
        const users = res.data.data || []
        const totalUsers = users.length
        const activeUsers = users.filter(u => u.status === 'ACTIVE').length
        const todayUsers = users.filter(u => isSameDay(u.createdAt)).length
        const growthRate = totalUsers > 0 ? formatPercent((todayUsers / totalUsers) * 100) : 0
        stats.value = { totalUsers, activeUsers, todayUsers, growthRate }
      } catch (e) {
        console.error('加载用户统计失败:', e)
      }
    }

    const formatDateTime = (isoString) => {
      if (!isoString) return ''
      const d = new Date(isoString)
      const pad = (n) => (n < 10 ? '0' + n : n)
      return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
    }

    const loadRecentActivities = async () => {
      const currentUser = store.getters.currentUser
      if (!currentUser || !currentUser.id) return

      try {
        const end = new Date()
        const start = new Date()
        start.setDate(end.getDate() - 30)
        const startDate = start.toISOString().slice(0,10)
        const endDate = end.toISOString().slice(0,10)

        const [recordsRes, affairsRes] = await Promise.all([
          studyApi.studyRecords.getRecordsByDateRange(currentUser.id, startDate, endDate),
          personalApi.affairs.getAffairs(currentUser.id)
        ])

        const records = (recordsRes.data.data || []).map(r => ({
          id: `sr-${r.id}`,
          time: formatDateTime(r.createTime || r.updateTime || r.studyDate),
          description: `学习记录：${r.subject}，时长 ${r.studyTime} 小时，效率 ${r.efficiencyScore || 1.0}`
        }))

        const affairs = (affairsRes.data.data || []).map(a => ({
          id: `pa-${a.id}`,
          time: formatDateTime(a.updateTime || a.endDate || a.startDate),
          description: `事务：${a.affairName}（评级 ${a.completionRating}）`
        }))

        const merged = [...records, ...affairs].filter(x => !!x.time)
        merged.sort((a,b) => new Date(b.time) - new Date(a.time))
        recentActivities.value = merged.slice(0, 8)
      } catch (e) {
        console.error('加载最近活动失败:', e)
        recentActivities.value = []
      }
    }

    const initUptime = () => {
      const start = Date.now()
      const tick = () => {
        const diff = Date.now() - start
        const minutes = Math.floor(diff / 60000)
        const hours = Math.floor(minutes / 60)
        const days = Math.floor(hours / 24)
        const h = hours % 24
        const m = minutes % 60
        uptime.value = `${days}天 ${h}小时 ${m}分钟`
      }
      tick()
      setInterval(tick, 60000)
    }

    onMounted(async () => {
      // 初始化认证信息，确保能获取当前用户
      store.dispatch('initializeAuth')
      await loadStats()
      await loadRecentActivities()
      initUptime()
    })
    
    return {
      stats,
      uptime,
      recentActivities
    }
  }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stat-icon.users {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.active {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.today {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.growth {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info h3 {
  margin: 0;
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.stat-info p {
  margin: 5px 0 0 0;
  color: #666;
  font-size: 14px;
}

.system-info p {
  margin: 10px 0;
  color: #666;
}

.system-info strong {
  color: #333;
}
</style>


